<template>
  <div class="precondition-editor">
    <n-space vertical>
      <!-- 字段列表 -->
      <div v-if="fields.length > 0">
        <VueDraggable
          v-model="fields"
          :animation="200"
          ghost-class="ghost-field"
          @end="onDragEnd"
        >
          <n-card
            v-for="(field, index) in fields"
            :key="index"
            size="small"
            class="mb-12px field-card"
            :bordered="true"
          >
            <template #header>
              <n-space justify="space-between" align="center">
                <n-space align="center">
                  <icon-park-outline-drag class="drag-handle cursor-move text-gray-400" />
                  <span>字段 {{ index + 1 }}</span>
                </n-space>
                <n-space>
                  <n-button
                    size="small"
                    quaternary
                    :disabled="index === 0"
                    @click="moveFieldUp(index)"
                    title="上移"
                  >
                    <template #icon>
                      <icon-park-outline-up />
                    </template>
                  </n-button>
                  <n-button
                    size="small"
                    quaternary
                    :disabled="index === fields.length - 1"
                    @click="moveFieldDown(index)"
                    title="下移"
                  >
                    <template #icon>
                      <icon-park-outline-down />
                    </template>
                  </n-button>
                  <n-button
                    size="small"
                    type="error"
                    quaternary
                    @click="removeField(index)"
                    title="删除"
                  >
                    <template #icon>
                      <icon-park-outline-delete />
                    </template>
                  </n-button>
                </n-space>
              </n-space>
            </template>

          <n-form
            :model="field"
            label-placement="left"
            label-width="80px"
            size="small"
          >
            <n-grid :cols="2" :x-gap="12">
              <n-grid-item>
                <n-form-item label="字段名称" required>
                  <n-input
                    v-model:value="field.name"
                    placeholder="如：age"
                    @blur="validateFieldName(field)"
                  />
                  <div v-if="field.nameError" class="field-error">{{ field.nameError }}</div>
                </n-form-item>
              </n-grid-item>
              <n-grid-item>
                <n-form-item label="显示标签" required>
                  <n-input
                    v-model:value="field.label"
                    placeholder="如：年龄"
                    @blur="updateConfig"
                  />
                </n-form-item>
              </n-grid-item>
            </n-grid>

            <n-grid :cols="2" :x-gap="12">
              <n-grid-item>
                <n-form-item label="字段类型" required>
                  <n-select
                    v-model:value="field.type"
                    :options="fieldTypeOptions"
                    @update:value="onFieldTypeChange(field)"
                  />
                </n-form-item>
              </n-grid-item>
              <n-grid-item>
                <n-form-item label="是否必填">
                  <n-switch
                    v-model:value="field.required"
                    @update:value="updateConfig"
                  />
                </n-form-item>
              </n-grid-item>
            </n-grid>

            <!-- 单选框/多选框选项配置 -->
            <n-form-item v-if="field.type === 'radio' || field.type === 'checkbox'" label="选项配置">
              <n-space vertical class="w-full">
                <n-space
                  v-for="(option, optionIndex) in field.options"
                  :key="optionIndex"
                  align="center"
                >
                  <n-input
                    v-model:value="field.options[optionIndex]"
                    placeholder="选项值"
                    @blur="updateConfig"
                  />
                  <n-button
                    size="small"
                    type="error"
                    quaternary
                    @click="removeOption(field, optionIndex)"
                  >
                    删除
                  </n-button>
                </n-space>
                <n-button
                  size="small"
                  type="primary"
                  dashed
                  @click="addOption(field)"
                >
                  添加选项
                </n-button>
              </n-space>
            </n-form-item>

            <!-- 数字类型配置 -->
            <n-grid v-if="field.type === 'number'" :cols="2" :x-gap="12">
              <n-grid-item>
                <n-form-item label="最小值">
                  <n-input-number
                    v-model:value="field.min"
                    placeholder="最小值"
                    @blur="updateConfig"
                  />
                </n-form-item>
              </n-grid-item>
              <n-grid-item>
                <n-form-item label="最大值">
                  <n-input-number
                    v-model:value="field.max"
                    placeholder="最大值"
                    @blur="updateConfig"
                  />
                </n-form-item>
              </n-grid-item>
            </n-grid>

            <!-- 字段预览 -->
            <n-form-item label="预览效果">
              <div class="field-preview">
                <FieldPreview :field="field" />
              </div>
            </n-form-item>
          </n-form>
        </n-card>
        </VueDraggable>
      </div>

      <!-- 空状态 -->
      <n-empty v-else description="暂无字段配置" size="small">
        <template #extra>
          <n-button size="small" @click="addField">添加第一个字段</n-button>
        </template>
      </n-empty>

      <!-- 添加字段按钮 -->
      <n-button
        v-if="fields.length > 0"
        type="primary"
        dashed
        block
        @click="addField"
      >
        <template #icon>
          <icon-park-outline-add-one />
        </template>
        添加字段
      </n-button>
    </n-space>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { VueDraggable } from 'vue-draggable-plus'
import FieldPreview from './FieldPreview.vue'
import { useMessage } from 'naive-ui'

interface PreconditionField {
  name: string
  label: string
  type: 'radio' | 'checkbox' | 'date' | 'number' | 'text'
  required: boolean
  options?: string[]
  min?: number
  max?: number
  nameError?: string // 添加错误信息字段
}

interface Props {
  modelValue?: { fields: PreconditionField[] } | null
}

interface Emits {
  (e: 'update:modelValue', value: { fields: PreconditionField[] } | null): void
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: null
})

const emit = defineEmits<Emits>()

// 字段列表
const fields = ref<PreconditionField[]>([])

// 字段类型选项
const fieldTypeOptions = [
  { label: '单选框', value: 'radio' },
  { label: '多选框', value: 'checkbox' },
  { label: '日期选择', value: 'date' },
  { label: '数字输入', value: 'number' },
  { label: '文本输入', value: 'text' }
]

const message = useMessage()

// 监听外部值变化
watch(
  () => props.modelValue,
  (newValue) => {
    if (newValue && newValue.fields) {
      fields.value = [...newValue.fields]
    } else {
      fields.value = []
    }
  },
  { immediate: true, deep: true }
)

// 添加字段
const addField = () => {
  fields.value.push({
    name: '',
    label: '',
    type: 'text',
    required: false
  })
  updateConfig()
}

// 删除字段
const removeField = (index: number) => {
  fields.value.splice(index, 1)
  updateConfig()
}

// 字段类型变化
const onFieldTypeChange = (field: PreconditionField) => {
  if ((field.type === 'radio' || field.type === 'checkbox') && !field.options) {
    field.options = ['']
  } else if (field.type !== 'radio' && field.type !== 'checkbox') {
    delete field.options
  }

  if (field.type !== 'number') {
    delete field.min
    delete field.max
  }

  updateConfig()
}

// 添加选项
const addOption = (field: PreconditionField) => {
  if (!field.options) {
    field.options = []
  }
  field.options.push('')
  updateConfig()
}

// 删除选项
const removeOption = (field: PreconditionField, index: number) => {
  if (field.options) {
    field.options.splice(index, 1)
    updateConfig()
  }
}

// 上移字段
const moveFieldUp = (index: number) => {
  if (index > 0) {
    const temp = fields.value[index]
    fields.value[index] = fields.value[index - 1]
    fields.value[index - 1] = temp
    updateConfig()
  }
}

// 下移字段
const moveFieldDown = (index: number) => {
  if (index < fields.value.length - 1) {
    const temp = fields.value[index]
    fields.value[index] = fields.value[index + 1]
    fields.value[index + 1] = temp
    updateConfig()
  }
}

// 拖拽结束事件
const onDragEnd = () => {
  updateConfig()
}

// 更新配置
const updateConfig = () => {
  if (fields.value.length === 0) {
    emit('update:modelValue', null)
  } else {
    emit('update:modelValue', { fields: [...fields.value] })
  }
}

// 验证字段名称
const validateFieldName = (field: PreconditionField) => {
  // 清除之前的错误
  field.nameError = undefined
  
  // 如果为空，不验证
  if (!field.name.trim()) {
    return
  }
  
  // 验证字段名称只包含英文字母、数字和下划线
  const nameRegex = /^[a-zA-Z0-9_]+$/
  if (!nameRegex.test(field.name)) {
    field.nameError = '字段名称只能包含英文字母、数字和下划线'
    message.warning('字段名称只能包含英文字母、数字和下划线')
    return
  }
  
  // 检查字段名称是否重复
  const duplicateField = fields.value.find(f => f !== field && f.name === field.name)
  if (duplicateField) {
    field.nameError = '字段名称不能重复'
    message.warning('字段名称不能重复')
    return
  }
  
  updateConfig()
}
</script>

<style scoped>
.precondition-editor {
  width: 100%;
  min-height: 400px;
}

.field-preview {
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e0e0e6;
}

.field-card {
  transition: all 0.3s ease;
  cursor: default;
  margin-bottom: 12px;
}

.field-card:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transform: translateY(-1px);
}

.drag-handle {
  cursor: move !important;
  transition: color 0.2s ease;
  font-size: 16px;
}

.drag-handle:hover {
  color: var(--primary-color) !important;
  transform: scale(1.1);
}

.ghost-field {
  opacity: 0.5;
  background: #f0f0f0;
  border: 2px dashed #ccc;
  transform: rotate(2deg);
}

.ghost-field * {
  visibility: hidden;
}

/* 优化空状态显示 */
.n-empty {
  padding: 40px 20px;
}



/* 优化按钮组 */
.n-space {
  flex-wrap: wrap;
}

/* 优化表单项间距 */
.n-form-item {
  margin-bottom: 12px;
}

.n-form-item:last-child {
  margin-bottom: 0;
}

/* 优化网格布局 */
.n-grid {
  width: 100%;
}

/* 优化选项配置区域 */
.n-space.vertical {
  width: 100%;
}

.field-error {
  color: #d03050;
  font-size: 12px;
  margin-top: 4px;
}
</style>
